package com.hjw.service.impl;

import com.hjw.dao.UserDao;
import com.hjw.entity.User;
import com.hjw.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * <p>Project:Academic - UserServiceImpl<p>
 *
 * @author IvanWei玮 -- maste
 * @version 1.0
 * @DataTime 2025/4/11 23:37
 * @since 1.8
 */
@Slf4j
@Primary
@Service
public class UserServiceImpl implements UserService {


    @Autowired
    private UserDao userDao;
    @Autowired
    private RedisTemplate<String, User> redisTemplate;


    @Override
    public List<User> findAll() {
        return userDao.findAll();
    }

    @Override
    public User findByAccount(String account) {
        return userDao.findByAccount(account);
    }

    @Override
    public User findById(Integer id) {
        User user = redisTemplate.opsForValue().get("user:" + id);
        if (user == null) {
            User u = userDao.findById(id);
            if (u != null) {
                redisTemplate.opsForValue().set("user:" + id, u,7200, TimeUnit.SECONDS);
            }
            log.info("数据库中获取得到user：{}",u);
            return u;
        }
        log.info("缓存中获取得到user：{}",user);
        return user;
    }

    @Override
    public List<User> findByCondition(Map<String, Object> map) {
        return userDao.findByCondition(map);
    }

    @Override
    @Transactional(rollbackFor = Exception.class , propagation = Propagation.NESTED)
    public int update(Map<String, Object> map) {
        if (map.get("id") == null) {
            throw new RuntimeException("id为空");
        }
        redisTemplate.delete("user:"+map.get("id"));
        int update = userDao.update(map);
        redisTemplate.delete("user:"+map.get("id"));
        return update;
    }

    @Override
    public int add(User user) {
        int add = userDao.add(user);
        if (add > 0) {
            redisTemplate.opsForValue().set("user:" + user.getId(), user);
        }
        return add;
    }

    @Override
    public int delete(Integer id) {
        redisTemplate.delete("user:" + id);
        int remove = userDao.remove(id);
        redisTemplate.delete("user:" + id);
        return remove;

    }
}
